# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""generate dataloader and data processing entry"""

import json
import os

import cv2
import numpy as np
import pycocotools.coco as coco
import scipy.io as sio

from mindvision.engine.class_factory import ClassFactory, ModuleType


@ClassFactory.register(ModuleType.DATASET)
class CenterfaceDataset():
    """
    Centerface dataset definition.
    """

    def __init__(self, annot_path, img_dir, split, max_objs=64, save_path=None):
        self.split = split
        self.max_objs = max_objs
        self.img_dir = img_dir
        self.annot_path = annot_path
        self.save_path = save_path

        print('==> getting centerface key point {} data.'.format(self.split))

        if self.split == 'train':
            self.coco = coco.COCO(self.annot_path)
            image_ids = self.coco.getImgIds()
            self.images = []
            for img_id in image_ids:
                idxs = self.coco.getAnnIds(imgIds=[img_id])
                if idxs:
                    self.images.append(img_id)
        elif self.split == 'test':
            ground_truth_mat = sio.loadmat(self.annot_path)
            event_list = ground_truth_mat['event_list']
            file_list = ground_truth_mat['file_list']
            self.images = []
            self.imgs_id = []
            img_id = 0
            load_dict = []
            for index, event in enumerate(event_list):
                file_list_item = file_list[index][0]
                im_dir = event[0][0]
                for file_obj in enumerate(file_list_item):
                    im_name = file_obj[0][0]
                    img_id = img_id + 1
                    zip_name = '%s/%s.jpg' % (im_dir, im_name)
                    img_path = os.path.join(self.img_dir, zip_name)
                    self.images.append(img_path)
                    self.imgs_id.append(img_id)
                    test_dict = {}
                    test_dict['im_dir'] = im_dir
                    test_dict['im_name'] = im_name
                    test_dict['im_id'] = img_id
                    load_dict.append(test_dict)
            with open(self.save_path, 'w') as f:
                f.write(json.dumps(load_dict))

        self.num_samples = len(self.images)
        print('Loaded {} {} samples'.format(self.split, self.num_samples))  # Loaded train 12671 samples

    def __getitem__(self, index):
        """
        Args:
            index (int): Index
        Returns:
            (image, target) (tuple): target is index of the target class.
        """
        if self.split == 'train':
            img_id = self.images[index]
            file_name = self.coco.loadImgs(ids=[img_id])[0]['file_name']
            img_path = os.path.join(self.img_dir, file_name)
            ann_ids = self.coco.getAnnIds(imgIds=[img_id])
            anns = self.coco.loadAnns(ids=ann_ids)
            num_objs = len(anns)
            if num_objs > self.max_objs:
                num_objs = self.max_objs
                anns = np.random.choice(anns, num_objs)
            # dataType ERROR to_list
            target = []
            for ann in anns:
                tmp = []
                tmp.extend(ann['bbox'])
                tmp.extend(ann['keypoints'])
                target.append(tmp)

            img = cv2.imread(img_path)
            return img, target

        img_path = self.images[index]
        img = cv2.imread(img_path)
        image_id = self.imgs_id[index]
        return img, image_id

    def __len__(self):
        return self.num_samples
